import { app } from 'db://app-game/core/app';
import { JsonUtil } from 'db://app-game/core/utils/JsonUtil';
import { AsyncQueue, NextFunction } from 'db://app-game/libs/collection/AsyncQueue';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { UIID } from '../../../../common/config/GameUIConfig';
import { Initialize } from '../Initialize';
import { InitializeViewComp } from '../view/InitializeViewComp';

/** 初始化游戏公共资源 */
@ecs.register('InitRes')
export class InitResComp extends ecs.Comp {
  reset() {}
}

/** 加载游戏资源 */
@ecs.register('Initialize')
export class InitResSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
  filter(): ecs.IMatcher {
    return ecs.allOf(InitResComp);
  }
  entityEnter(e: Initialize): void {
    var queue: AsyncQueue = new AsyncQueue();

    // 加载自定义资源
    this.loadCustom(queue);

    // 加载游戏内容加载进度提示界面
    this.onComplete(queue, e);

    queue.play();
  }

  /** 加载自定义内容 */
  private loadCustom(queue: AsyncQueue) {
    // 加载所有配置表格到缓存中
    queue.push((next: NextFunction, params: any, args: any) => {
      JsonUtil.loadDirAsync().then(() => {
        console.log('加载所有配置表格到缓存中完成');
        next();
      });
    });
  }

  /** 加载完成进入游戏内容加载界面 */
  private onComplete(queue: AsyncQueue, e: Initialize) {
    queue.complete = async () => {
      // 2. 加载游戏内容加载界面
      var node = await app.gui.openAsync(UIID.Initialize);
      if (node) e.add(node.getComponent(InitializeViewComp)!);
      e.remove(InitResComp);
    };
  }
}
